package com.zy.ems.common.handler;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * SQL注入拦截器 <br/>
 * date: 2016年3月25日 下午4:27:37 <br/>
 *
 * @author sunshine
 * @version
 * @since JDK 1.7
 */
public class SqlInjectIntercepter implements HandlerInterceptor {

    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
    }

    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object arg2) throws Exception {
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String[] values = request.getParameterValues(name);
            for (int i = 0; i < values.length; i++) {
                if (hasAttackStr(values[i])) {
                    if (!(values[i].equals("DELETE")
                            && name.equals("_method"))) {
                        response.setContentType("text/html;charset=utf-8");
                        response.getWriter().print(
                                "请不要尝试注入<br><a href='#' onclick='history.go(-1)'>返回</a>");
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public static boolean hasAttackStr(String str) {
        String attstr = "'|and|exec|insert|select|delete|update|count|chr|mid|master|truncate|char|declare|--|script|varchar|WHERE|UPDATE%09|%09";
        String[] atts = attstr.split("\\|");
        for (int i = 0; i < atts.length; i++) {
            if (str.toLowerCase().indexOf(atts[i].toLowerCase()) != -1) {
                System.out.println("!~~~~~attack str :" + str + ":" + atts[i]);
                return true;
            }
        }
        return false;
    }
}
